package com.cxyzy.demo

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.widget.Toast
import io.objectbox.Box
import io.objectbox.kotlin.boxFor
import io.objectbox.kotlin.query
import io.objectbox.query.Query
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private lateinit var notesBox: Box<Note>
    private lateinit var notesQuery: Query<Note>
    private lateinit var notesAdapter: NotesAdapter
    private val dataList: MutableList<Note> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        notesBox = ObjectBox.boxStore.boxFor()
        notesQuery = notesBox.query {
            order(Note_.text)
        }
        loadData()
        initViews()
        addIv.setOnClickListener { addNote() }
    }

    private fun initViews() {
        notesAdapter = NotesAdapter(this, dataList)
        with(recyclerView)
        {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = notesAdapter
        }
        notesAdapter.onItemClickListener = object : OnItemClickListener {
            override fun OnItemClick(position: Int) {
                Toast.makeText(this@MainActivity, dataList[position].text, Toast.LENGTH_LONG).show()
            }
        }

    }

    private fun addNote() {
        val note = Note(text = "text", comment = "comment")
        notesBox.put(note)
        loadData()
        notesAdapter.notifyDataSetChanged()
    }

    private fun loadData() {
        val notes = notesQuery.find()
        dataList.clear()
        dataList.addAll(notes)
    }
}
